package com.lagou.edu.dao;

import com.lagou.edu.pojo.Resume;
import com.lagou.edu.util.DataSourceUtil;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Service
public class ResumeDaoImpl implements ResumeDao {

    private JdbcTemplate jdbcTemplate = DataSourceUtil.getJdbcTemplate();

    @Override
    public List<Resume> findAll() {
        String sql = "select * from tb_resume";
        return jdbcTemplate.query(sql, new RowMapper<Resume>() {
            @Override
            public Resume mapRow(ResultSet resultSet, int i) throws SQLException {
                Resume resume = new Resume();
                resume.setId(resultSet.getLong("id"));
                resume.setName(resultSet.getString("name"));
                resume.setAddress(resultSet.getString("address"));
                resume.setPhone(resultSet.getString("phone"));
                return resume;
            }
        });
    }

    @Override
    public Resume findById(long id) {
        String sql = "select * from tb_resume where id=?";
        return jdbcTemplate.queryForObject(sql, new RowMapper<Resume>() {
            @Override
            public Resume mapRow(ResultSet resultSet, int i) throws SQLException {
                Resume resume = new Resume();
                resume.setId(resultSet.getLong("id"));
                resume.setName(resultSet.getString("name"));
                resume.setAddress(resultSet.getString("address"));
                resume.setPhone(resultSet.getString("phone"));
                return resume;
            }
        }, id);
    }

    @Override
    public void insert(Resume resume) {
        String sql = "insert into tb_resume(name,address,phone) VALUE(?,?,?)";
        jdbcTemplate.update(sql,resume.getName(),resume.getAddress(), resume.getPhone());
    }

    @Override
    public void update(Resume resume) {
        String sql = "update tb_resume set name=?,address=?,phone=? WHERE id = ?";
        jdbcTemplate.update(sql,resume.getName(),resume.getAddress(), resume.getPhone(), resume.getId());

    }

    @Override
    public void deleteById(long id) {
        String sql = "delete from tb_resume where id = ?";
        jdbcTemplate.update(sql, id);
    }
}
